// 确认订单
<template>
	<view class="container">
		<template v-if="init">
			<!-- v-if="isNeedAddress == null" -->
			<view class="address padding">
				<SelectAddress v-model="address" :isShowPhone="true"></SelectAddress>
			</view>
			<SplitLine></SplitLine>
			<view class="products">
				<!-- 遍历 products 数组，为每个 item 渲染 SkuItem 组件 -->
				<SkuItem class="sku" :info="item.sku" v-for="(item, index) in products"></SkuItem>
			</view>
			<SplitLine></SplitLine>
			<view class="list padding">
				<view class="list-item">
					<view class="body">
						商品总价
					</view>
					<view class="arrow-right bold">
						<view>
							{{ order.totalPrice }}晶石
							<!-- <PriceDisplay :info="order" prefix="product_"></PriceDisplay> -->
						</view>
						<!-- <text class="meta">¥{{order.product_price | priceToFixed}}</text> -->
					</view>
				</view>
				<view class="list-item">
					<view class="body">
						<!-- 优惠券 -->
						红包可用
					</view>
					<view class="arrow-right bold" v-if="currentCoupon.id" @tap="couponsVisible = true">
						<text class="meta red">- ¥{{ order.coupon_discount || (currentCoupon.discountMoney *
							10).toFixed(2) }}</text>
						<text class="new-iconfont icon-arrow-right"></text>
					</view>
					<view class="arrow-right" v-else @tap="couponsVisible = true">
						<text class="meta" v-if="usableCoupons.length">{{ usableCoupons.length }}张可用</text>
						<text class="meta" v-else>无可用</text>
						<text class="new-iconfont icon-arrow-right"></text>
					</view>
				</view>
				<!-- 
				<view class="list-item" v-if="order.cover_type">
					<view class="body">
						兑换类型
					</view>
					<view class="arrow-right bold">
						<text class="meta" v-if="order.cover_type === 'chip'">碎片兑换</text>
						<text class="meta" v-else-if="order.cover_type === 'score'">{{scoreAlias}}兑换</text>
					</view>
				</view> -->

				<!-- 		<view class="list-item" v-if="order.cover_discount">
					<view class="body">
						兑换优惠
					</view>
					<view class="arrow-right bold">
						<text class="meta red">- ¥{{order.cover_discount | priceToFixed}}</text>
					</view>
				</view> -->

				<!-- 		<view class="list-item">
					<view class="body">
						红包抵扣
					</view>
					<view class="arrow-right bold">
						<text class="meta red"> <template v-if="order.redpack">-</template>
¥{{order.redpack | priceToFixed}}</text>
<switch v-if="order.redpack" class="redpack-switch" :checked="order.is_use_redpack" @change="redpackSwitchChange" />
</view>
</view> -->
				<!-- 潮玩币抵扣 -->
				<!-- 	<view class="list-item" v-if="order.max_useable_score">
					<view class="body">
						{{scoreAlias}}抵扣
					</view>
					<view class="arrow-right bold">
						<text class="meta"> {{order.max_useable_score}}{{scoreAlias}}</text>
						<text class="meta red" style="margin-left: 10rpx;" v-if="order.score_discount">
							-¥{{order.score_discount | priceToFixed}}</text>
						<switch v-if="order.max_useable_score" class="redpack-switch" :checked="order.is_use_score"
							@change="scoreSwitchChange" />
					</view>
				</view> -->
				<view class="list-item">
					<view class="body">
						运费
					</view>
					<view class="arrow-right bold" v-if="order.carriage_type === 2">
						<text class="meta red">到付</text>
					</view>
					<view class="arrow-right bold" v-else>
						<text class="meta red">¥{{ order.carriage }}</text>
					</view>
				</view>
				<view class="list-item">
					<view class="body">
						实付
					</view>
					<view class="arrow-right bold">
						<text class="meta">{{ order.payPrice }}晶石</text>
					</view>
				</view>
				<view class="list-item">
					<view class="body">
						备注
					</view>
					<view class="arrow-right remark">
						<input type="text" v-model="remark" placeholder="请输入您对商家说的话" placeholder-class="placeholder" />
					</view>
				</view>
			</view>
			<view style="height:160upx;"></view>
			<view class="footer-actions safe-area-bottom">
				<view class="price-c">
					<!--  || -->
					{{ order.payPrice }}晶石
					<!-- <OrderPrice :now-price="totalPrice/100"></OrderPrice> -->
					<!-- <PriceDisplay :info="order" prefix="pay_"></PriceDisplay> -->
				</view>
				<IButton class="submit-btn" round size="small" @click="createOrder">
					<text>确认订单</text>
				</IButton>
			</view>
			<UsableCouponPopup v-if="couponsVisible" :unusableCoupons="unusableCoupons" :usableCoupons="usableCoupons"
				:currentCoupon="currentCoupon" :totalprice="order.totalPrice" @change="couponChange"
				@close="couponsVisible = false">
			</UsableCouponPopup>

		</template>
		<view style="height: 60vh;overflow: hidden;" v-else>
			<NoData></NoData>
		</view>

	</view>
</template>

<script>
/***12行
<!-- 遍历 products 数组，为每个 item 渲染产品项 -->
<view class="product-item padding" :class="{'border-bottom': index !== products.length - 1}" v-for="(item,index) in products" :key="item.id">
<!-- 显示产品缩略图 -->
<image :src="item.products.thumb" class="thumb" mode="aspectFill"></image>
 
<!-- 产品信息区域 -->
<view class="product-info">
<!-- 产品标题 -->
<view class="product-title">
  {{item.products.title}}
</view>
 
<!-- 产品属性 -->
<view class="attrs gray">
  <text>{{item.skus.attrs | productAttrsToString}}</text>
</view>
 
<!-- 价格和数量信息 -->
<view class="price-count">
  <!-- 使用 PriceDisplay 组件显示价格信息 -->
  <PriceDisplay :info="item"></PriceDisplay>
  <text style="flex-grow: 1;"></text> <!-- 弹性占位符，将后面的内容推至最右边 -->
  <text>x{{item.total}}</text> <!-- 显示产品数量-->
</view>
</view>
</view>
	
	
*/
import mixin from "@/utils/mixin.js"
import SplitLine from "@/components/SplitLine/index.vue";
import IButton from "@/components/Button/index.vue";
import payment from "@/utils/payment.js"
import {
	mapGetters
} from "vuex"
export default {
	mixins: [mixin],
	components: {
		SplitLine,
		IButton,
	},
	data() {
		return {
			address: {},
			order: {
				is_use_redpack: 'unselect'
			},
			isNeedAddress: null,
			skus: [],
			seckillId: '',
			groupPriceUuid: '',
			products: [],
			remark: '',
			init: false,
			couponsVisible: false,
			unusableCoupons: [],
			usableCoupons: [],
			currentCoupon: {},
			current: 0,
			animationData: {},
			animationData2: {},
			coverType: '',
			_source: '',
			submitorder: {},
			nodeId: ""
		}
	},
	computed: {
		...mapGetters(['token']),
		totalPrice() {
			let total = this.order.price;
			return total
		},
		payPrice() {
			let pay = this.order.price;
			return pay
		},
	},
	onLoad(e) {
		// console.log(e.skus)
		this.seckillId = e.seckillId
		this.groupPriceUuid = e.groupPriceUuid
		this.coverType = e.coverType
		this.skus = JSON.parse(e.skus)
		this._source = e._source
		this.nodeId = e.nodeId
		// debugger
		console.log(this.skus);
		// console.log(this.order.totalPrice);

		uni.$on('selectAddress', res => {
			this.address = res
			// this.getOrderInfo()
		})
	},
	onUnload() {
		uni.$off('selectAddress', data => {
			console.log('移除 selectAddress 自定义事件');
		})
	},
	onShow() {
		if (this.token && !this.address.id) {
			this.getOrderInfo()
		}
		// console.log(this.order);
		// console.log("token", products.uniqueToken);

	},
	methods: {
		redpackSwitchChange(e) {
			this.order.is_use_redpack = e.detail.value ? 1 : 0
			this.getOrderInfo()
		},
		scoreSwitchChange(e) {
			this.order.is_use_score = e.detail.value ? 1 : 0
			this.getOrderInfo()
		},
		couponChange(e) {
			if (e.id === this.currentCoupon.id) {
				// 再次点击取消使用优惠券  // 暂时关闭此功能
				this.currentCoupon = {}
				this.getOrderInfo()
			} else {
				this.currentCoupon = e
				if (this.order.carriage != 0) {
					this.order.payPrice = ((this.order.carriage * 10) + this.order.totalPrice) - (this.currentCoupon.discountMoney * 10).toFixed(2)
				} else {
					this.order.payPrice = this.order.totalPrice - (this.currentCoupon.discountMoney * 10).toFixed(2)
				}
				if (this.order.payPrice < 0) {
					console.log("payPrice", this.order.payPrice);
					console.log(this.order.carriage);
					if (this.order.carriage != 0) {
						
						this.order.payPrice = this.order.carriage * 10
					} else {
						this.order.payPrice = 0
					}
				}
				
				console.log("totalPrice", this.order.totalPrice);
				// this.getOrderInfo()
			}
		},
		createOrder() {
			if (this.isNeedAddress && (!this.address || !this.address.id)) {
				uni.showToast({
					title: "未添加收货地址",
					icon: "none"
				})
				return
			}
			uni.showLoading({
				title: '加载中',
				mask: true
			})
			// const sku = [{
			// 	skuId: this.skus[0].skuId,
			// 	total: this.skus[0].total
			// }];
			const sku = [];
			for (let i = 0; i < this.skus.length; i++) {
				sku.push({
					skuId: this.skus[i].skuId,
					total: this.skus[i].total
				})
			}
			if (this.order.carriage != 0) {
				this.order.totalPrice = (this.order.carriage * 10) + this.order.totalPrice
			}

			const confirmOrder = {
				sku: sku,
				redpackId: this.currentCoupon.id || "", // 优惠券id
				totalPrice: this.order.totalPrice || "", // 总价
				payPrice: this.order.payPrice, //  支付价格
				addressId: this.address.id || "", // 地址id
				carriage: this.order.carriage || "", // 运费
				note: this.remark || "", // 备注
				uniqueToken: this.order.uniqueToken || ""
			};
			console.log("confirmOrder", confirmOrder)
			if (this.nodeId) {
				console.log();
				let that = this
				uni.showModal({
					title: '支付提示',
					content: '请支付',
					success: function (res) {
						if (res.confirm) {
							that.$http(`/zb-seckill/paySeckillOrder/${that.nodeId}/${that.skus[0].skuId}/${that.address.id}`,
								'POST').then(res => {
									// 如果状态码等于200，则提示用户支付成功，并在2秒之后跳转页面
									if (res.code == 200) {
										uni.hideLoading()
										uni.showToast({
											title: '支付成功~',
											icon: 'none'
										})
										console.log("支付成功");
										setTimeout(() => {
											uni.redirectTo({
												url: "/pages/orderList/index"
											})
										}, 2000)
										return false
										// 如果状态码不等于200，则提示用户余额不足，并在2秒之后跳转页面
									} else {
										uni.showToast({
											title: '余额不足~',
											icon: 'none'
										})
										setTimeout(() => {
											uni.redirectTo({
												url: "/pages/orderList/index"
											})
										}, 2000)
										return false
									}
								});
						} else if (res.cancel) {
							console.log('取消');
							uni.navigateTo({
								url: "/pages/orderList/index"
							})
						}
					}
				});
			} else {
				this.$http("/zb-order/confirmOrder", 'POST', confirmOrder).then(res => {
					console.log(res);
					console.log(confirmOrder.uniqueToken);
					// 判断上一个接口的返回状态是否满足你的条件，比如状态码为 200
					if (res.code === 200) {
						this.submitorder = res.data
						this.payOrder(this.submitorder)

					} else {
						// 如果上一个接口的返回状态不满足条件
						console.error("上一个接口返回状态不为200，处理错误或其他操作");
					}
					// if (!info.is_need_pay) {
					// 	uni.showToast({
					// 		title: "支付成功，正在跳转~",
					// 		icon: "none"
					// 	})
					// 	setTimeout(() => {
					// 		uni.redirectTo({
					// 			url: "/pages/orderDetail/index?uuid=" + order.uuid
					// 		})
					// 	}, 1500)
					// 	return false
					// }

					// // 进行支付
					// payment.pay({
					// 	...info,
					// 	pay_type: info.pay_type,
					// 	success: () => {
					// 		uni.showToast({
					// 			title: "支付成功",
					// 			icon: "none"
					// 		})
					// 		setTimeout(() => {
					// 			uni.redirectTo({
					// 				url: "/pages/orderList/index?status=deliver_pending"
					// 			})
					// 		}, 1500)
					// 	},
					// 	fail: () => {
					// 		uni.showToast({
					// 			title: "支付失败",
					// 			icon: "none"
					// 		})
					// 		uni.redirectTo({
					// 			url: "/pages/orderDetail/index?uuid=" + order.uuid
					// 		})
					// 	}
					// })

					uni.hideLoading()
				}).catch(err => {
					uni.hideLoading()
				})

			}

			// 	this.$api.emit('order.store', {
			// 		payment: 'miniapp',
			// 		skus: this.skus,
			// 		couponId: this.currentCoupon && this.currentCoupon.id,
			// 		seckill_id: this.seckillId,
			// 		group_price_uuid: this.groupPriceUuid,
			// 		address_id: this.address && this.address.id,
			// 		remark: this.remark,
			// 		cover_type: this.coverType,
			// 		is_use_redpack: this.order.is_use_redpack,
			// 		is_use_score: this.order.is_use_score,
			// 		_source: this._source
			// 	}).then(res => {
			// 		let info = res.data
			// 		let order = res.data.order
			// 		if (!info.is_need_pay) {

			// 			uni.showToast({
			// 				title: "支付成功，正在跳转~",
			// 				icon: "none"
			// 			})

			// 			setTimeout(() => {
			// 				uni.redirectTo({
			// 					url: "/pages/orderDetail/index?uuid=" + order.uuid
			// 				})
			// 			}, 1500)

			// 			return false
			// 		}

			// 		// 进行支付
			// 		payment.pay({
			// 			...info,
			// 			pay_type: info.pay_type,
			// 			success: () => {
			// 				uni.showToast({
			// 					title: "支付成功",
			// 					icon: "none"
			// 				})
			// 				setTimeout(() => {
			// 					uni.redirectTo({
			// 						url: "/pages/orderList/index?status=deliver_pending"
			// 					})
			// 				}, 1500)
			// 			},
			// 			fail: () => {
			// 				uni.showToast({
			// 					title: "支付失败",
			// 					icon: "none"
			// 				})
			// 				uni.redirectTo({
			// 					url: "/pages/orderDetail/index?uuid=" + order.uuid
			// 				})
			// 			}
			// 		})

			// 		uni.hideLoading()
			// 	}).catch(err => {
			// 		uni.hideLoading()
			// 	})
		},
		payOrder(submitorder) {

			if (this.isNeedAddress && (!this.address || !this.address.id)) {
				uni.showToast({
					title: "未添加收货地址",
					icon: "none"
				})
				return
			}
			let that = this
			uni.showModal({
				title: '支付提示',
				content: '请支付',
				success: function (res) {
					if (res.confirm) {
						console.log(submitorder);
						const uuid = submitorder.uuid
						const uniqueToken = submitorder.uniqueToken
						// 调用支付接口
						that.$http("/zb-order/payScore", 'POST', {
							"uuid": uuid,
							"uniqueToken": uniqueToken
						}).then(res => {
							// 如果状态码等于200，则提示用户支付成功，并在2秒之后跳转页面
							if (res.code == 200) {
								uni.showToast({
									title: '支付成功~',
									icon: 'none'
								})
								console.log("支付成功");
								setTimeout(() => {
									uni.redirectTo({
										url: "/pages/orderList/index"
									})
								}, 2000)
								return false
								// 如果状态码不等于200，则提示用户余额不足，并在2秒之后跳转页面
							} else {
								uni.showToast({
									title: '余额不足~',
									icon: 'none'
								})
								setTimeout(() => {
									uni.redirectTo({
										url: "/pages/orderList/index"
									})
								}, 2000)
								return false
							}
						});
					} else if (res.cancel) {
						console.log('取消');
						uni.navigateTo({
							url: "/pages/orderList/index"
						})
					}
				}
			});

			// 微信小程序请求订阅消息
			// #ifdef MP-WEIXIN
			uni.requestSubscribeMessage({
				tmplIds: [
					this.miniappSubscribeIds.order_delivered, // 发货提醒
					this.miniappSubscribeIds.order_paid, // 支付成功通知
				],
				complete: (res) => {
					// this.createOrder()
				}
			})
			// #endif
			// #ifndef MP-WEIXIN
			// this.createOrder()
			// #endif
		},
		getOrderInfo() {
			// if (!this.address) {
			// 	return false
			// }
			uni.showLoading({
				title: '加载中',
				mask: true
			})
			this.skus[0].total = this.skus[0].total.num ? this.skus[0].total.num : this.skus[0].total
			this.skus[0].issCart = false
			if (!this.nodeId) {
				this.$http("/zb-order/settle", 'post', this.skus
					// {
					// 	skus: this.skus,
					// 	address_id: this.address && this.address.id,
					// 	seckill_id: this.seckillId,
					// 	group_price_uuid: this.groupPriceUuid,
					// 	couponId: this.currentCoupon.id,
					// 	cover_type: this.coverType,
					// 	is_use_redpack: this.order.is_use_redpack,
					// 	is_use_score: this.order.is_use_score ? 1 : 0,
					// }
				).then(res => {
					// console.log(res);
					uni.hideLoading()
					if (res.code == 500) {
						uni.showModal({
							content: res.message,
							title: '温馨提示'
						})
					} else {
						this.init = true
						this.order = res.data
						this.order.payPrice = res.data.totalPrice
						if (this.order.carriage != 0) {
							this.order.payPrice = (this.order.carriage * 10) + this.order.payPrice
						}
						this.address = res.data.addresses
						this.products = res.data.shop
						this.unusableCoupons = res.data.coupon.unusable
						this.usableCoupons = res.data.coupon.usable
						this.isNeedAddress = res.data.tip
						// console.log(this.products[0].products.thumb);
						// 提示一些信息： 如活动库存不足够，将按原价结算
						if (res.data.tip) {
							uni.showModal({
								content: res.data.tip,
								title: '温馨提示'
							})
						}
					}
				})
			} else {
				this.skus[0].nodeId = this.nodeId
				this.$http("/zb-seckill/seckill", 'post', this.skus).then(res => {
					uni.hideLoading()
					if (res.code == 200) {
						this.init = true
						this.order = res.data
						this.address = res.data.addresses
						this.products = res.data.shop
						this.unusableCoupons = res.data.coupon.unusable
						this.usableCoupons = res.data.coupon.usable
						this.isNeedAddress = res.data.tip
						// console.log(this.products[0].products.thumb);
					} else {
						uni.showModal({
							content: res.message,
							title: '温馨提示'
						})
					}
				})
			}
		}
	}
}
</script>

<style lang="scss" scoped>
page {
	background: linear-gradient(to right bottom, #090919, #233a47) !important;
}

.list-item {
	display: flex;
	align-items: center;
	position: relative;
}

.submit-btn {
	background: rgb(108, 67, 255) !important;
	color: #fff;
	background-image: none;
}

.tag {
	color: #fff;
}

.list-item .body {
	flex: 1;
	display: flex;
	align-items: center;
}

.list-item-title {
	flex: 1;
}

.redpack-switch {
	margin-left: 20rpx;
	position: relative;
	left: 10rpx;
}

.address {
	flex: 1;
}

.products {}

.list-item {
	height: 80upx;

	.body {
		font-size: 28upx;
		color: #fff;
	}

	.arrow-right {
		display: flex;
		align-items: center;

		&.bold {
			font-weight: bold;
			color: #fff;
		}

		.icon-arrow-right {
			font-size: 50rpx;
			margin-right: -14rpx;
			color: #fff;
		}
	}

	.meta {
		font-size: 26upx;
		color: #fff;
	}

	.remark {
		input {
			height: 100%;
			text-align: right;
			color: #fff;
			font-size: 28upx;
			width: 600upx;

			.placeholder {
				color: #fff;
			}
		}
	}
}



.footer-actions {
	width: 100%;
	position: fixed;
	bottom: 0;
	left: 0;
	display: flex;
	align-items: center;
	justify-content: space-between;
	// background-color: #ffffff;
	background: linear-gradient(to right bottom, #090919, #233a47);
	box-shadow: 0 -6upx 8upx rgba(206, 206, 206, 0.3);
	padding: 0 24upx;
	box-sizing: border-box;

	.price-c {
		height: 114upx;
		display: flex;
		align-items: center;
		font-size: 46upx;
		color: #fff;
	}
}
</style>